package oom;

import sun.misc.Unsafe;

import java.lang.reflect.Field;
import java.util.concurrent.TimeUnit;

/**
 * -Xmx20m -XX:MaxDirectMemorySize=10M
 */
public class DirectMemoryDemo {
    final static long M1 = 1024 * 1024;
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, InterruptedException {
        Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafe.setAccessible(true);
        Unsafe unsafe = (Unsafe) theUnsafe.get(null);
        int i = 0;
        for(;;) {
            unsafe.allocateMemory(M1);
            TimeUnit.MILLISECONDS.sleep(10);
            System.out.println(i ++);
            if(i > 30)
                break;
        }
    }
}
